package com.hjm.admin.moule.view.fragment.impl;

import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.hjm.admin.moule.R;
import com.hjm.admin.moule.db.helpter.CollBookHelper;
import com.hjm.admin.moule.model.LocalFileBean;
import com.hjm.admin.moule.utils.FileStack;
import com.hjm.admin.moule.utils.FileUtils;
import com.hjm.admin.moule.view.adapter.LocalFileAdapter;
import com.hjm.admin.moule.view.base.BaseFileFragment;
import com.hjm.admin.moule.viewmodel.BaseViewModel;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;

public class FileCategoryFragment extends BaseFileFragment {
    @BindView(R.id.file_category_tv_path)
    TextView mTvPath;
    @BindView(R.id.file_cate_tv_back_last)
    TextView mTvBackLast;
    @BindView(R.id.file_category_iv_back_last)
    ImageView mIvBackLast;
    @BindView(R.id.rv_file_category)
    RecyclerView mRvFileCategory;
    List<LocalFileBean> mFileBeans = new ArrayList<>();
    private FileStack mFileStack;

    public static FileCategoryFragment newInstance() {
        return new FileCategoryFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return setContentView(container, R.layout.fragment_file_category, new BaseViewModel(mContext));
    }

    @Override
    protected void initView() {
        mFileStack = new FileStack();
        mAdapter = new LocalFileAdapter(mFileBeans);
        mRvFileCategory.setLayoutManager(new LinearLayoutManager(mContext));
        mRvFileCategory.addItemDecoration(new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL));
        mRvFileCategory.setAdapter(mAdapter);

        File root = Environment.getExternalStorageDirectory();
        toggleFileTree(root);
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            File file = mFileBeans.get(position).getFile();
            if (file.isDirectory()) {
                FileStack.FileSnapshot snapshot = new FileStack.FileSnapshot();
                snapshot.filePath = mTvPath.getText().toString();
                snapshot.files = new ArrayList<>(mAdapter.getAllFiles());
                snapshot.scrollOffset = mRvFileCategory.computeVerticalScrollOffset();
               Log.e("--",mFileStack.toString()) ;
                mFileStack.push(snapshot);
                Log.e("++",mFileStack.toString()) ;
                toggleFileTree(file);
            } else {
                String id = file.getAbsolutePath();
                if (CollBookHelper.getsInstance().findBookById(id) != null) {
                    return;
                }
                mAdapter.setCheckedItem(position);
                if (mListener != null) {
                    mListener.onItemCheckedChange(mAdapter.getItemIsChecked(position));
                }
            }
        });
        mTvBackLast.setOnClickListener(v -> onClick());
        mIvBackLast.setOnClickListener(v -> onClick());
    }

    public void onClick() {
        FileStack.FileSnapshot snapshot = mFileStack.pop();
        int oldScrollOffset = mRvFileCategory.computeVerticalScrollOffset();
        if (snapshot == null) return;
        mTvPath.setText(snapshot.filePath);
        addFiles(snapshot.files);
        mRvFileCategory.scrollBy(0, snapshot.scrollOffset - oldScrollOffset);
        if (mListener != null)
            mListener.onCategoryChanged();
    }

    private void addFiles(List<File> files) {
        mFileBeans.clear();
        for (File file : files) {
            LocalFileBean localFileBean = new LocalFileBean();
            localFileBean.setSelect(false);
            localFileBean.setFile(file);
            mFileBeans.add(localFileBean);
        }
        mAdapter.notifyDataSetChanged();

    }

    private void toggleFileTree(File root) {
        mTvPath.setText(getString(R.string.wy_file_path, root.getPath()));
        File[] files = root.listFiles(new SimpleFileFilter());
        List<File> rootFiles = Arrays.asList(files);
        Collections.sort(rootFiles, new FileCompatator());
        addFiles(rootFiles);
        if (mListener != null) {
            mListener.onCategoryChanged();
        }

    }

    public class SimpleFileFilter implements FileFilter {
        @Override
        public boolean accept(File pathname) {
            if (pathname.getName().startsWith(".")) return false;
            if (pathname.isDirectory() && pathname.list().length == 0) return false;
            if (!pathname.isDirectory() && (pathname.length() == 0 || !pathname.getName().endsWith(FileUtils.SUFFIX_TXT)))
                return false;
            return true;
        }
    }

    public class FileCompatator implements Comparator<File> {

        @Override
        public int compare(File o1, File o2) {
            if (o1.isDirectory() && o2.isFile()) {
                return -1;
            }
            if (o2.isDirectory() && o1.isFile()) {
                return 1;
            }
            return o1.getName().compareToIgnoreCase(o2.getName());
        }
    }
}
